package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import bean.User;
public class AuthFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        // 当前访问的路由
        String uri = request.getRequestURI();

        // 判断是否在白名单
        if (Urls.equals(uri)) {
            System.out.println("用户已登录或在白名单，放行。");
            chain.doFilter(request, response);
            return;
        }


        User user = (User) request.getSession().getAttribute("user");
        if (null == user) {
            System.out.printf("%s:用户未登录,AuthFilter进行拦截!\n", this.getClass().getSimpleName());
            response.sendRedirect("login.jsp");
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) {

    }

}

class Urls {
    static boolean equals(String uri) {
        ArrayList<String> allow = new ArrayList<>();
        // 在这里加上放行名单
        allow.add("login");
        allow.add("login.jsp");
        allow.add("/");
        allow.add("/register.html");
        allow.add("/register");



        ArrayList<Boolean> result = new ArrayList<>();
        for (String s : allow) {
            result.add(uri.endsWith(s));
        }

        return result.contains(true);
    }
}